#include "ImageFileThumb.h"
#include <QtCore/QDir>
#include <assert.h>
#include <QtCore/QFileInfo>
//#include <QtCore/QBuffer>

ImageFileThumb::ImageFileThumb(const QString& absDirPath)
:_dirPath(absDirPath),_fileSize(0)
{
	assert(QDir::isAbsolutePath(_dirPath));
}

ImageFileThumb::~ImageFileThumb()
{

}

void ImageFileThumb::renameFile(const QString& fn){
	_fileName=fn;
}

void ImageFileThumb::setFileName(const QString& fn){
	_fileName=fn;
	QFileInfo imgFileInfo(absoluteFilePath());
	_fileSize=imgFileInfo.size();
	_lastModifyTime=imgFileInfo.lastModified();
	_image=QImage();
}

QString ImageFileThumb::fileName() const{
	return _fileName;
}

QString ImageFileThumb::absoluteFilePath() const{
	return QFileInfo(_dirPath+"/"+_fileName).absoluteFilePath();
}

QImage ImageFileThumb::image() const{
	static QImage loadingImg(":/imgs/loading.PNG");
	if (_image.isNull())
		return loadingImg;
	else
		return _image;
}

bool ImageFileThumb::isDirty() const{
	QFileInfo imgFileInfo(absoluteFilePath());
	if (!imgFileInfo.exists())
		return true;

	if (imgFileInfo.size()!=_fileSize)
		return true;

	if (imgFileInfo.lastModified()!=_lastModifyTime)
		return true;

	return false;
}

void ImageFileThumb::setThumbImage(const QImage& image){
	_image=image;
}

bool ImageFileThumb::isValid() const{
	return QFile::exists(absoluteFilePath()) 
		/*&& !_image.isNull() && !_fileName.isEmpty() && _fileSize>0 && _lastModifyTime.isValid()*/
		;
}

QDataStream& operator<<(QDataStream & stream,const ImageFileThumb& thumb){
	stream<<thumb._fileName<<thumb._fileSize<<thumb._lastModifyTime<<thumb._image;
	return stream;
}

QDataStream & operator>> ( QDataStream & stream, ImageFileThumb& thumb){
	stream>>thumb._fileName>>thumb._fileSize>>thumb._lastModifyTime>>thumb._image;
	return stream;
}
